package ldh.im.fxgui.stage;

import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import ldh.im.fxbase.util.CloseFactory;
import ldh.im.fxbase.util.MovableHelper;
import ldh.im.fxbase.util.RegionUtil;
import ldh.im.fxgui.controller.WebRtcAudioController;
import ldh.im.fxgui.handle.WebRtcUserChangeEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Set;

public class AudioStage extends BaseStage implements WebRtcUserChangeEvent {

    private static final Logger LOGGER = LoggerFactory.getLogger(AudioStage.class);

    private WebRtcAudioController audioController;

    public AudioStage(String name) {
        super(name);
    }

    /**
     *
     * @param invitationUserId  视频邀请人
     * @param roomName
     * @param userIdSet
     */
    public void doOpenAudioPane(String invitationUserId, String roomName, Set<String> userIdSet) {
        RegionUtil.FxmlBean<VBox, WebRtcAudioController> fxmlBean = RegionUtil.loadFxmlBean(getClass().getResource("/fxml/WebRtcAudioPage.fxml"));
        fxmlBean.getController().setStageName(name);
        Scene scene = new Scene(fxmlBean.getNode(), this.calcWidth(userIdSet), this.calcHeight(userIdSet));
        MovableHelper.movable(fxmlBean.getNode());
        scene.setFill(null);
        loadStyleFiles(scene);

        audioController = fxmlBean.getController();

        try {
            Stage stage = createStage(scene);
            stage.setOnCloseRequest(e->{
                try {
                    CloseFactory.getInstance().remove(name);
                    fxmlBean.getController().close();
                } catch (Exception ee) {
                    LOGGER.error(fxmlBean.getController().getClass().getName() + ".close error: ", ee);
                }
            });

            fxmlBean.getController().setParams(invitationUserId, roomName, userIdSet, VIDEO_WIDTH, VIDEO_HEIGHT);
        } catch (Exception e) {
            LOGGER.error("语音通信失败", e);
        }
    }

    @Override
    public void close() throws IOException {
        super.close();
        if (audioController != null) {
            audioController.close();
        }
    }

    @Override
    public void userSizeChanged(Set<String> userIds) {

    }
}
